package com.czwj.action;

import java.io.File;
import java.io.FileInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czwj.annotation.SystemControllerLog;
import com.czwj.entities.Attachment;
import com.czwj.entities.OperateResult;
import com.czwj.service.AttachmentService;

@Controller
public class AttachmentAction {
	@Resource
	AttachmentService attachmentService;

	@SystemControllerLog(description = "删除附件") 
	@RequestMapping(value = "/attachmentDelete.do", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult attachmentDelete(@RequestParam("id") int id) throws Exception {
		OperateResult result = new OperateResult();
		int count = 0;
		count = attachmentService.delete(id);
		result.setSuccess(count > 0);
		return result;
	}
	
	@RequestMapping(value = "/attachmentFile.do", method = RequestMethod.GET)
	@ResponseBody
	public void attachmentdownLoad(@RequestParam("id") int id,HttpServletResponse response) throws Exception {
		Attachment attachment = attachmentService.selectByPrimaryKey(id);
		File file = new File(attachment.getPath());
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition","attachment;filename=" + attachment.getName());
		response.setContentLength((int) file.length());
	    
	    FileInputStream fis = null;
	    try {
	        fis = new FileInputStream(file);
	        byte[] buffer = new byte[1024];
	        int count = 0;
	        while ((count = fis.read(buffer)) > 0) {
	        	response.getOutputStream().write(buffer, 0, count);
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	    	response.getOutputStream().flush();
	    	response.getOutputStream().close();
	        fis.close();
	        System.out.println("finish");
	    }
	}
}
